from aiohttp import web

from .container import Container

# 成功
STATE_SUCCESS = 0
# 失败
STATE_FAILED = 500


def ret_obj(data=None, code: int = 0, msg: str = ""):
    return {"code": code, "data": data, "msg": code_msg(code, msg)}


def ret_failed(msg: str = ""):
    return {"code": STATE_FAILED, "data": None, "msg": code_msg(STATE_FAILED, msg)}


def code_msg(code: int = 0, msg: str = ""):
    if msg != "":
        return msg
    msgObj = {STATE_SUCCESS: "Success", STATE_FAILED: "Failed"}
    return msgObj.get(code, msg)


def resp_json(data):
    # 临结束后处理
    # Container.handle_end()
    return web.json_response(data_value_2_str(data))


def data_value_2_str(data):
    if isinstance(data, list):
        new_data = []
        for v in data:
            new_data.append(data_value_2_str(v))
        return new_data
    elif isinstance(data, dict):
        for k in data:
            v = data[k]
            data[k] = data_value_2_str(v)
        return data
    elif isinstance(data, str):
        return data
    elif not isinstance(data, str):
        return str(data)
    return data
